<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 确认收货
 *
 * @author      Eden
 * @datetime    2016/12/1 22:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Confirm_Model extends API_Model
{

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (!$this->checkParams($params) || !$this->checkOrder($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $data = array(
                'status' => 'Complete',
                'compTime' => dateTime()
            );

            $this->db->where(array('sn' => $params['sn'], 'userId' => $params['userId']));
            $this->db->update('user_order', $data);

            if ($this->db->affected_rows()) {
                $send['state'] = true;
                $send['data'] = array(
                    'msg' => '交易完成'
                );
            } else {
                $send['error'] = '订单状态修改失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function checkParams($params = array())
    {
        if (empty($params['userId']) || empty($params['sn'])) {
            $this->setError('参数错误');
            return false;
        }
        return true;
    }

    /**
     * 检查订单是否有效
     * @param array $params
     * @return bool
     */
    private function checkOrder($params = array())
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order', array('userId' => $params['userId'], 'sn' => $params['sn']));
        $row = $q->row_array();
        if (empty($row)) {
            $this->setError('无效订单号');
            return false;
        }

        if ($row['status'] == 'Complete') {
            $this->setError('订单已结束, 无法更改');
            return false;
        }

        return true;
    }
}

